import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import type { ApiResponse } from '@/types'

// 生成幂等性Key
const generateIdempotencyKey = (): string => {
  return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
}

// 创建axios实例
const createAxiosInstance = (): AxiosInstance => {
  const instance = axios.create({
    baseURL: '',
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json',
    },
  })

  // 请求拦截器
  instance.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      // 添加认证头
      const token = localStorage.getItem('accessToken')
      if (token && config.headers) {
        config.headers.Authorization = `Bearer ${token}`
      }

      // 添加幂等性Key（所有非GET请求）
      if (config.method && ['post', 'put', 'delete'].includes(config.method.toLowerCase()) && config.headers) {
        config.headers['Idempotency-Key'] = generateIdempotencyKey()
      }

      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  // 响应拦截器
  instance.interceptors.response.use(
    (response: AxiosResponse<ApiResponse>) => {
      const { success, message, data } = response.data
      if (success) {
        return data
      } else {
        ElMessage.error(message || '请求失败')
        return Promise.reject(new Error(message))
      }
    },
    (error) => {
      const { response } = error
      if (response) {
        const { status, data } = response
        switch (status) {
          case 401:
            ElMessage.error('未授权，请重新登录')
            // 清除token，跳转到登录页
            localStorage.removeItem('accessToken')
            localStorage.removeItem('refreshToken')
            window.location.href = '/login'
            break
          case 403:
            ElMessage.error('拒绝访问')
            break
          case 404:
            ElMessage.error('请求的资源不存在')
            break
          case 500:
            ElMessage.error('服务器内部错误')
            break
          default:
            ElMessage.error(data?.message || '请求失败')
        }
      } else {
        ElMessage.error('网络错误，请检查网络连接')
      }
      return Promise.reject(error)
    }
  )

  return instance
}

// 导出axios实例
export const request = createAxiosInstance()

// 导出默认实例
export default request
